package com.kobeliu.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kobeliu.base.BaseInfoProperties;
import com.kobeliu.enums.DealStatus;
import com.kobeliu.enums.JobStatus;
import com.kobeliu.mapper.JobMapper;
import com.kobeliu.pojo.Job;
import com.kobeliu.pojo.bo.QueryReportBO;
import com.kobeliu.pojo.mo.ReportMO;
import com.kobeliu.repository.ReportJobRepository;
import com.kobeliu.service.ReportService;
import com.kobeliu.utils.LocalDateUtils;
import com.kobeliu.utils.PagedGridResult;
import com.tencentcloudapi.hcm.v20181106.models.EvaluationRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class ReportServiceImpl extends BaseInfoProperties implements ReportService {

    @Autowired
    private ReportJobRepository repository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private JobMapper jobMapper;

    @Override
    public void saveReportRecord(ReportMO mo) {

        mo.setDealStatus(DealStatus.WAITING.type);
        mo.setCreatedTime(LocalDateTime.now());
        mo.setUpdatedTime(LocalDateTime.now());
        repository.save(mo);
    }

    @Override
    public boolean isReportRecordExist(String reportUserId, String jobId) {

        ReportMO isExist = repository.findByReportUserIdAndJobId(reportUserId, jobId);

        return isExist!=null;

    }

    @Override
    public PagedGridResult findReportPage(QueryReportBO bo) {

        String endTime = bo.getEndDate();
        String beginTime = bo.getBeginDate();
        LocalDateTime beginDate = null;
        LocalDateTime endDate = null;
        if(StringUtils.isNotBlank(beginTime)){
            beginDate = LocalDateUtils.parseLocalDateTime(beginTime,LocalDateUtils.DATETIME_PATTERN);
        }
        if(StringUtils.isNotBlank(endTime)){
            endDate = LocalDateUtils.parseLocalDateTime(endTime,LocalDateUtils.DATETIME_PATTERN);
        }

        String companyName = bo.getCompanyName();
        String jobName = bo.getJobName();
        String reportUserName = bo.getReportUserName();
        Integer dealStatus = bo.getDealStatus();

        //1.创建查询对象
        Query query = new Query();
        //2.创建查询条件
//        Criteria criteria = new Criteria();

        //模糊搜索
//        Pattern pattern = Pattern.compile("^.*"+jobName+".*$");
//        query.addCriteria(Criteria.where("job_name").regex(pattern));
        //设置查询条件参数 模糊查询
        if(StringUtils.isNotBlank(companyName)){
            query = addLikeByValue(query,"company_name",companyName);
        }
        if(StringUtils.isNotBlank(jobName)){
            query = addLikeByValue(query,"job_name",jobName);
        }
        if(StringUtils.isNotBlank(reportUserName)){
            query = addLikeByValue(query,"report_user_name",reportUserName);
        }

        if(dealStatus != null){
            query.addCriteria(Criteria.where("deal_status").is(dealStatus));
        }
        if(beginDate!=null && endDate == null){
            query.addCriteria(Criteria.where("created_time").gte(beginDate));
        }else if(beginDate==null && endDate != null){
            query.addCriteria(Criteria.where("created_time").lte(endDate));
        }else if(beginDate!=null && endDate != null){
            query.addCriteria(Criteria
                    .where("created_time")
                    .gte(beginDate)
                    .lte(endDate));
        }

        //分页前查询
        long count = mongoTemplate.count(query, ReportMO.class);

        //分页查询数据
        Pageable pageable = PageRequest.of(bo.getPage()-1,
                bo.getLimit(),
                Sort.Direction.DESC,
                "created_time");
        query.with(pageable);

        List<ReportMO> mos = mongoTemplate.find(query, ReportMO.class);

        //自建pageList
        PageInfo<ReportMO> pageList = new PageInfo<>(mos);
        PagedGridResult result = new PagedGridResult();
        result.setRows(mos);
        result.setPage(bo.getPage());
        result.setRecords(pageList.getTotal());
        result.setTotal(count);
        return result;


    }

    @Override
    public void updateReportRecordStatus(String reportId, DealStatus status) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(reportId));

        if(status == DealStatus.DONE){
            //即删除岗位
            ReportMO reportMO = repository.findById(reportId).get();

            String jobId= reportMO.getJobId();
            Job job = new Job();
            job.setId(jobId);
            job.setUpdatedTime(LocalDateTime.now());
            job.setStatus(JobStatus.DELETE.type);
            job.setViolateReason(reportMO.getReportReason());
            jobMapper.updateById(job);

            Job selected = jobMapper.selectById(jobId);
            //删除缓存
            redis.del(REDIS_JOB_DETAIL +
                    ":"+selected.getCompanyId()+
                    ":"+selected.getHrId()+":"+
                    jobId);
        }

        //更新
        Update update = new Update();
        update.set("deal_status",status.type);
        update.set("updated_time",LocalDateTime.now());
        mongoTemplate.updateFirst(query,update,ReportMO.class);
    }

    private Query addLikeByValue(Query query,String key,String value){
        //模糊查询
        Pattern pattern = Pattern.compile("^.*"+value+".*$");
        query.addCriteria(Criteria.where(key).regex(pattern));
        return  query;
    }
}
